import React, { useEffect } from 'react';
import { useAiCorrectorStore } from '@/stores/useAiCorrectorStore';
import { CorrectionStatus } from '@/types/aiCorrector';
import { useBusiness } from '@/stores/useBusinessStore';
import {
  ItemSelector,
  CorrectionProgress,
  ResultsOverview,
  IssueList,
  ExportButton
} from '@/components/aiCorrector';

// 内部组件，使用上下文
const AICorrectorContent: React.FC = () => {
  const { 
    state, 
    resetCorrection
  } = useAiCorrectorStore();
  
  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-zinc-800">AI智能检测</h1>
        
        {state.status === CorrectionStatus.COMPLETED && (
          <div className="flex gap-3">
            <button
              onClick={resetCorrection}
              className="px-4 py-2 rounded-lg bg-zinc-100 hover:bg-zinc-200 text-zinc-800 font-medium transition-colors flex items-center"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 15l-3-3m0 0l3-3m-3 3h8M3 12a9 9 0 1118 0 9 9 0 01-18 0z" />
              </svg>
              重新选择检查项
            </button>
            <ExportButton />
          </div>
        )}
      </div>
      
      {/* 选择检查项和执行检测部分 */}
      {(state.status === CorrectionStatus.IDLE || 
        state.status === CorrectionStatus.SELECTING || 
        state.status === CorrectionStatus.PROCESSING) && (
        <>
          <CorrectionProgress />
          <ItemSelector />
        </>
      )}
      
      {/* 检测结果部分 */}
      {state.status === CorrectionStatus.COMPLETED && (
        <>
          <ResultsOverview />
          <IssueList />
        </>
      )}
    </div>
  );
};

// 主页面组件
const AICorrectorPage: React.FC = () => {
  const { selectedBusiness } = useBusiness();
  return <AICorrectorPageContent businessId={selectedBusiness?.id} />;
};

// 内部内容组件
const AICorrectorPageContent: React.FC<{ businessId?: string }> = ({ businessId }) => {
  const { initFromServer, state } = useAiCorrectorStore();
  const [isInitialized, setIsInitialized] = React.useState(false);

  // 合并后的单一副作用：首次加载 & 数据自愈
  useEffect(() => {
    if (!businessId) return;

    const loadData = async () => {
      // 场景 1：首次挂载或业务切换
      if (!isInitialized) {
        console.log(111)
        await initFromServer(businessId);
        setIsInitialized(true);
        return;
      }

      // 场景 2：已初始化，但列表意外为空且无任何筛选条件
      const noActiveFilters =
        state.filters.searchTerm === '' &&
        state.filters.type === 'all' &&
        state.filters.progressStatus === 'all';

      if (state.filteredItems.length === 0 && noActiveFilters) {
        console.log(222)
        await initFromServer(businessId);
      }
    };

    loadData();
  }, [businessId]);

  return <AICorrectorContent />;
};

export default AICorrectorPage;
